package com.cloudfun.campusshare.device.protocol.listener;

import com.cloudfun.campusshare.device.protocol.handler.AliyunIotMsgHandler;
import com.cloudfun.campusshare.device.protocol.handler.DefaultAliyunIotMsgHandler;
import com.cloudfun.campusshare.util.ByteUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.jms.Message;
import javax.jms.MessageListener;
import java.util.List;

/**
 * Created by Huqin on 2019/12/21
 */
@Slf4j
@Component
public class AliyunIotMsgListener implements MessageListener {

    @Autowired
    private List<AliyunIotMsgHandler> aliyunIotMsgHandlers;

    @Autowired
    private DefaultAliyunIotMsgHandler defaultAliyunIotMsgHandler;

    @Override
    public void onMessage(Message message) {
        try {
            long start = System.currentTimeMillis();
            // 日志
            String topic = message.getStringProperty("topic");
            String messageId = message.getStringProperty("messageId");
            String timestamp = message.getStringProperty("generateTime");
            String body = topic.endsWith("user/update") ? ByteUtil.bytesToHexString(message.getBody(byte[].class)) : new String(message.getBody(byte[].class));

            log.info("receive message, topic = {}, messageId = {}, generateTime = {}, content = {}", topic, messageId, timestamp, body);
            // 处理
            boolean processed = false;
            for (AliyunIotMsgHandler aliyunIotMsgHandler : aliyunIotMsgHandlers) {
                if (aliyunIotMsgHandler.support(message)) {
                    aliyunIotMsgHandler.handle(message);
                    processed = true;
                    break;
                }
            }
            if (!processed) {
                defaultAliyunIotMsgHandler.handle(message);
            }
            //如果创建Session选择的是Session.CLIENT_ACKNOWLEDGE，这里需要手动ACK。
            message.acknowledge();
            log.info("消息:{}处理耗时：{}ms", messageId, System.currentTimeMillis() - start);
            //如果要对收到的消息做耗时的处理，请异步处理，确保这里不要有耗时逻辑。
        } catch (Exception e) {
            log.error("处理阿里云IOT消息时异常：", e);
        }
    }

}
